import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message, Tabs } from 'antd';
import React, { useState } from 'react';
import { ProFormText, LoginForm } from '@ant-design/pro-form';

// @ts-ignore
import { history, useModel } from 'umi';
import Footer from '@/components/Footer';
import styles from './index.less';
import { REG_CODE } from '@/utils/constants';
import { isSuccessful } from '@/utils/utils';
import {OpUser} from "@/services/api-functions";

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<any>({});
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();

    if (userInfo) {
      await setInitialState((s: any) => ({ ...s, currentUser: userInfo }));
    }
  };

  const handleSubmit = (values: any) => {
    OpUser.login({ ...values }).then(async (response: any) => {
      const { data } = response;

      if (isSuccessful(response)) {
        message.success('🎉 🎉 🎉  登录成功！');
        await fetchUserInfo();

        if (data) {
          await setInitialState((s: any) => ({ ...s, currentUser: data }));
        }
        /** 此方法会跳转到 redirect 参数所在的位置 */

        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as {
          redirect: string;
        };
        history.push(redirect || '/');
        return;
      } else {
        // 如果失败去设置用户错误信息
        setUserLoginState(response.msg);
      }
    });
  };

  const { status, type: loginType } = userLoginState;
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm logo={<img alt="logo" src="/logo.png" />} title="即刻刷题" subTitle=''
          onFinish={async (values) => await handleSubmit(values as any)}>

          <Tabs activeKey={type} onChange={setType}><Tabs.TabPane key="account" tab='账户密码登录' /></Tabs>

          {status === 'error' && loginType === 'account' && (<LoginMessage content='用户名或密码错误' />)}

          {type === 'account' && (<>
              <ProFormText
                name="account"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder="请输入账号"
                rules={[
                  {
                    required: true,
                    message: '请输入账号!',
                  },
                  // {
                  //   pattern: REG_CODE.EMAIL_OR_CELLPHONE,
                  //   message: '账号格式错误！',
                  // },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder="请输入密码!"
                rules={[
                  {
                    required: true,
                    message: '请输入密码!',
                  },
                ]}
              />
            </>)}

          <div style={{marginBottom: 24, display: 'none',}}>
            <a style={{float: 'right',}}>忘记密码</a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
